package sk.naive.talker.server;

import sk.naive.talker.util.PropertyConfiguration;
import sk.naive.talker.persistence.*;
import sk.naive.talker.props.Property;

import java.util.Set;

/**
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.8 $ $Date: 2005/02/16 19:27:21 $
 */
public abstract class PersistentObjectFactory {
	protected PropertyConfiguration propertyConfiguration;

	public PersistentObjectFactory(String propertiesBundleName) {
		propertyConfiguration = new PropertyConfiguration(propertiesBundleName);
	}

	public PersistentObjectFactory(PropertyConfiguration propertyConfiguration) {
		this.propertyConfiguration = propertyConfiguration;
	}

	public PersistentObject create(String name) throws PersistenceException {
		DbTransaction.begin();
		DbLayer db = new DbLayer();
		Integer id = db.create(getType());
		db.storeProperty(id, getNamingProperty(), name);
		DbTransaction.finish();
		return getPersistentObjectByName(name);
	}

	public void remove(PersistentObject object) throws PersistenceException {
		new DbLayer().remove(object.getId());
	}

	public PersistentObject getPersistentObjectByName(String name) throws PersistenceException {
		return getPersistentObject(getId(name));
	}

	public PersistentObject getPersistentObject(Integer id) throws PersistenceException {
		PersistentObject po = persistentObjectInstance(id);
		new DbLayer().loadProperties(po);
		return po;
	}

	public PropertyConfiguration getPropertyConfiguration() {
		return propertyConfiguration;
	}

	protected abstract int getType();

	protected abstract String getNamingProperty();

	protected abstract PersistentObject persistentObjectInstance(Integer id) throws PersistenceException;

	protected Integer getId(String name) throws PersistenceException {
		return new DbLayer().objectId(getType(), getNamingProperty(), name);
	}

	public Property getProperty(String key) {
		return propertyConfiguration.getProperty(key);
	}

	public Set getPersistent() {
		return propertyConfiguration.getPersistent();
	}

	protected Set<Integer> objectIdList() throws PersistenceException {
		return new DbLayer().objectIdList(getType());
	}
}
